package com.acme.javaschool.sems.ionio.serialization.net;

import com.acme.javaschool.sems.ionio.serialization.SensorData;
import com.acme.javaschool.sems.ionio.serialization.Serializer;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;


public class SerializationServer {

    private final Serializer<SensorData> serializer;

    public SerializationServer(Serializer<SensorData> serializer) {
        this.serializer = serializer;
    }

    public void work(int port) {

        try (ServerSocket serverSocket = new ServerSocket(port);
             Socket socket = serverSocket.accept();
             DataInputStream in = new DataInputStream(socket.getInputStream());
             DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        ) {
            int objectsNum = in.readInt();
            System.out.println("[server] Gonna receive " + objectsNum + " objects.");
            SensorData[] receivedObjects = new SensorData[objectsNum];
            for (int i = 0; i < objectsNum; i++) {
                receivedObjects[i] = serializer.deserialize(in);
            }
            out.writeInt(objectsNum);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
